// @flow
import React, { Component } from 'react'
import styles from './CustomersAdd.css'
import { Form, Input, Button, Select, message, Upload, Icon } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import CustomerContactList from 'components/CustomerContactList'
const FormItem = Form.Item
const Option = Select.Option
const Dragger = Upload.Dragger
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}
type Props = {
  form: Object,
  history: Object
}

type States = {
  industries: Array<Object>,
  customerTypes: Array<Object>,
  loading: boolean,
  provinces: Array<Object>,
  districts: Array<Object>,
  cities: Array<Object>,
  users: Array<Object>,
  imageUrl: string,
  remoteImageUrl: string,
  contactData: Array<Object>,
  fileList: Array<Object>,
  province: string,
  district: string,
  city: string,
  longitude: string, // 经度
  latitude: string // 纬度
}
class CustomersAdd extends Component {
  props: Props
  state: States
  getIndustry: Function
  getUsers: Function
  getCustomerType: Function
  getProvinces: Function
  submit: Function
  goBack: Function
  changeProvince: Function
  changeCity: Function
  keyPressEvent: Function
  changeFile: Function
  changeFile1: Function
  beforeUpload: Function
  checkNum: Function
  getContact: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      industries: [],
      customerTypes: [],
      loading: false,
      provinces: [],
      cities: [],
      districts: [],
      imageUrl: '',
      remoteImageUrl: '',
      users: [],
      contactData: [],
      fileList: [],
      province: '',
      district: '',
      city: '',
      longitude: '', // 经度
      latitude: '' // 纬度
    }
    this.getIndustry = this.getIndustry.bind(this)
    this.getUsers = this.getUsers.bind(this)
    this.getCustomerType = this.getCustomerType.bind(this)
    this.submit = this.submit.bind(this)
    this.goBack = this.goBack.bind(this)
    this.changeProvince = this.changeProvince.bind(this)
    this.getProvinces = this.getProvinces.bind(this)
    this.changeCity = this.changeCity.bind(this)
    this.changeFile = this.changeFile.bind(this)
    this.changeFile1 = this.changeFile1.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
    this.checkNum = this.checkNum.bind(this)
    this.getContact = this.getContact.bind(this)
    // this.keyPressEvent = this.keyPressEvent.bind(this)
  }

  componentWillMount () {
    this.getIndustry()
    // this.getUsers() // 获得所有用户（联系人处使用）
    this.getCustomerType()
    this.getProvinces()
  }
  // componentDidMount () {
  //   document.onkeypress = this.keyPressEvent
  // }
  // componentWillUnmount () {
  //   document.onkeypress = null
  // }
  // keyPressEvent (e) {
  //   const keyCode = e.keyCode || e.which
  //   if (keyCode === 13) {
  //     this.submit()
  //   }
  // }
  checkNum (rule, value, callback) {
    const checkReg = /^[a-zA-Z][a-zA-Z0-9_]*$/
    if (value && !checkReg.test(value)) {
      callback('只能以英文开头, 且只能包含英文,数字和下划线')
    } else {
      callback()
    }
  }
  changeFile (info) {
    const response = info.file.response
    if (response && response.code === 200000) {
      this.setState({
        imageUrl: response.result.name,
        remoteImageUrl: response.result.url
      })
    }
  }
  changeFile1 (info) {
    let fileList = info.fileList
    // 1. Limit the number of uploaded files
    //    Only to show two recent uploaded files, and old ones will be replaced by the new
    fileList = fileList.slice(-10)
    // 2. read from response and show file link
    fileList = fileList.map((file) => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.result.url
        file.name = file.name
      }
      return file
    })
    // 3. filter successfully uploaded files according to response from server
    fileList = fileList.filter((file) => {
      const status = info.file.status
      if (status === 'done') {
        return file.response.status === 'success'
      }
      return true
    })
    this.setState({ fileList: fileList })
  }

  beforeUpload (file) {
    const type = file.type.toLocaleLowerCase()
    if (type.indexOf('image/') === -1) {
      message.error('只能上传图片', 3)
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片必须小于2MB!')
    }
    return type.indexOf('image/') > -1
  }
  changeProvince (value) {
    const values = value.split('_')
    universalFetch(`${__SERVICE_API__}sys/regions/city?province=${values[0]}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }

        this.setState({
          cities: json.result,
          province: values[0],
          longitude: values[1],
          latitude: values[2]
        })
        this.props.form.resetFields(['city', 'district'])
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  changeCity (value) {
    const values = value.split('_')
    // const { getFieldsValue, resetFields } = this.props.form
    // const { province } = getFieldsValue()
    const { province } = this.state
    universalFetch(`${__SERVICE_API__}sys/regions/district?province=${province}&city=${values[0]}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }

        this.setState({
          districts: json.result,
          city: values[0],
          longitude: values[1],
          latitude: values[2]
        })
        this.props.form.resetFields(['district'])
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  changeDistrict = (value) => {
    const values = value.split('_')
    this.setState({
      district: values[0],
      longitude: values[1],
      latitude: values[2]
    })
  }
  getProvinces () {
    universalFetch(`${__SERVICE_API__}sys/regions/province`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          provinces: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getContact (data: Array<Object>) {
    this.setState({
      contactData: data
    })
  }
  submit (e) {
    e.preventDefault()
    const { form } = this.props
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        loading: true
      })
      const { imageUrl, fileList, contactData } = this.state
      const values = {
        ...Object.assign({}, fieldsValue, { imageUrl })
      }
      const values1 = {
        ...Object.assign({}, values, { fileList }),
        'contacts': contactData,
        province: this.state.province,
        district: this.state.district,
        city: this.state.city,
        longitude: this.state.longitude,
        latitude: this.state.latitude
      }
      values1.fileList = values.fileUrl ? values.fileUrl.fileList : []
      console.log(values1)
      universalFetch(`${__SERVICE_API__}device/customers`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(values1)
      })
        .then(res => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          this.setState({
            loading: false
          })
          message.success('客户添加成功')
          this.props.history.push('/business/customer')
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
          message.error('客户添加失败')
          this.setState({
            loading: false
          })
        })
    })
  }

  goBack () {
    this.props.history.push('/business/customer')
  }
  getIndustry () {
    universalFetch(`${__SERVICE_API__}device/conditions?types=industry`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          industries: json.result.industry
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getUsers () {
    universalFetch(`${__SERVICE_API__}sys/users?pageSize=20000`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          users: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getCustomerType () {
    universalFetch(`${__SERVICE_API__}device/conditions?types=customerType`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          customerTypes: json.result.customerType
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  changeLongitude = (e) => {
    this.setState({
      longitude: e.target.value
    })
  }
  changeLatitude = (e) => {
    this.setState({
      latitude: e.target.value
    })
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const { industries, customerTypes, loading, provinces,
      cities, districts, remoteImageUrl } = this.state
    const token = localStorage.getItem('asset_token')

    const props1 = {
      name: 'file',
      multiple: true,
      showUploadList: true,
      headers:{ 'X-Auth':token },
      action: `${__SERVICE_API__}static/statics`,
      onChange: this.changeFile1
    }
    return (
      <div className={styles['main']}>
        <Form onSubmit={this.submit}>
          {/* <FormItem {...formItemLayout} label='客户编号' hasFeedback>
            {
              getFieldDecorator('customerNo', {
                rules: [
                  { required: true, message: '请填写客户编号', whitespace: true }
                  // { validator: this.checkNum }
                ]
              })(
                <Input placeholder='请填写客户编号' ref={(e) => {
                  document.querySelector('#customerNo').focus()
                }} />
              )
            }
          </FormItem> */}
          <FormItem {...formItemLayout} label='客户名称' hasFeedback>
            {
              getFieldDecorator('name', {
                rules: [
                  { required: true, message: '请填写客户名称', whitespace: true }
                ]
              })(
                <Input placeholder='请填写客户名称' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='省'>
            {
              getFieldDecorator('province', {
                rules: [
                  { required: true, message: '请选择省' }
                ]
              })(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择省' onChange={this.changeProvince}>
                  {
                    provinces.map((province, i) => {
                      return <Option key={i}
                        value={province.province + '_' + province.longitude + '_' + province.latitude}>
                        {province.province}
                      </Option>
                    })
                  }
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='市'>
            {
              getFieldDecorator('city', {
              })(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择市' onChange={this.changeCity}>
                  {
                    cities.map((city, i) => {
                      return <Option key={i}
                        value={city.city + '_' + city.longitude + '_' + city.latitude}>
                        {city.city}
                      </Option>
                    })
                  }
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='区'>
            {
              getFieldDecorator('district', {
              })(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择区' onChange={this.changeDistrict}>
                  {
                    districts.map((district, i) => {
                      return <Option key={i}
                        value={district.district + '_' + district.longitude + '_' + district.latitude}>
                        {district.district}
                      </Option>
                    })
                  }
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='详细地址' hasFeedback>
            {
              getFieldDecorator('address', {})(
                <Input placeholder='请填写详细地址' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='地理坐标(经度)' hasFeedback>
            {
              <Input value={this.state.longitude} placeholder='请填写地理坐标(经度)'
                onChange={this.changeLongitude} />
            }
          </FormItem>
          <FormItem {...formItemLayout} label='地理坐标(纬度)' hasFeedback>
            {
              <Input value={this.state.latitude} placeholder='请填写地理坐标(纬度)'
                onChange={this.changeLatitude} />
            }
          </FormItem>
          <FormItem {...formItemLayout} label='所属行业'>
            {
              getFieldDecorator('industry', {})(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择所属行业'>
                  {
                    industries.map((item, i) => {
                      return <Option key={i} value={item.value}>
                        {item.label}
                      </Option>
                    })
                  }
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='客户类型'>
            {
              getFieldDecorator('type', {})(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择客户类型'>
                  {
                    customerTypes.map((item, i) => {
                      return <Option key={i} value={item.value}>
                        {item.label}
                      </Option>
                    })
                  }
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='联系人'>
            {getFieldDecorator('contacts')(
              <CustomerContactList contactData={[]} getContact={this.getContact} />
            )}
          </FormItem>
          {
            // <FormItem {...formItemLayout} label='联系人' hasFeedback>
            //   {
            //     getFieldDecorator('contactPerson', {})(
            //       // <Input placeholder='请填写联系人' />
            //       <Select showSearch
            //         filterOption={(input, option) => {
            //           return option.props.children.indexOf(input) >= 0
            //         }} placeholder='请选择联系人'>
            //         {
            //           users.map((item, i) => {
            //             return <Option key={i} value={item.loginName}>
            //               {item.loginName}
            //             </Option>
            //           })
            //         }
            //       </Select>
            //     )
            //   }
            // </FormItem>
            // <FormItem {...formItemLayout} label='联系方式' hasFeedback>
            //   {
            //     getFieldDecorator('mobile', {})(
            //       <Input placeholder='请填写联系方式' />
            //     )
            //   }
            // </FormItem>
          }

          <FormItem {...formItemLayout} label='客户图片'>
            {
              getFieldDecorator('imageUrl', {})(
                <Upload
                  {...{
                    name: 'file',
                    className: styles['avatar-uploader'],
                    action: `${__SERVICE_API__}static/statics`,
                    headers:{ 'X-Auth':token },
                    onChange: this.changeFile,
                    beforeUpload: this.beforeUpload,
                    showUploadList: false
                  }}
                  >
                  {
                    remoteImageUrl
                    ? <div className={styles['image-preview']}>
                      <img src={remoteImageUrl} style={{ width: '100%' }} />
                      <div className={styles['over-avatar']}>
                        更换图片
                      </div>
                    </div>
                    : <Button style={{ width: '150px' }}>
                      <Icon type='upload' />上传图片
                    </Button>
                  }
                </Upload>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='客户文件'>
            {
              getFieldDecorator('fileUrl', {})(
                <Dragger {...props1}>
                  <p className='ant-upload-drag-icon'>
                    <Icon type='inbox' />
                  </p>
                  <p className='ant-upload-text'>点击或者拖拽文件到该区域</p>
                  <p className='ant-upload-hint'>支持单个或批量上传</p>
                </Dragger>
              )
            }
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type='primary'
              loading={loading}
              htmlType='submit'
              >
              保存
            </Button>
            <Button
              onClick={this.goBack}
              style={{ marginLeft: '20px' }}
              >
              返回
            </Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

export default Form.create()(CustomersAdd)
